import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth.js'
import { getUserInfo, getUserDetailById, login } from "@/api/user.js";
import router, { resetRouter } from "@/router"

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    userId: null
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
      setTimeStamp()
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    logout(state) {
      state.userInfo = {};
      state.token = '';
      removeToken();
      router.push('/login')
    },
    setId(state, id) {
      state.userId = id
    }
  },
  actions: {
    async getUserInfo(context) {
      console.log(123);
      const data = await getUserInfo();
      const data1 = await getUserDetailById(data.userId);
      const userInfo = { ...data, ...data1 };
      context.commit('setUserInfo', userInfo)
      context.commit('setId', userInfo.id)
      return userInfo
    },
    async login(context, data) {
      const token = await login(data);
      context.commit('setToken', token)
      router.push('/dashboard')
    },
    logout(context) {
      resetRouter();
      context.commit('permission/setRoutes', [], { root: true })
      context.commit('logout');
    }
  }
}
